package com.dm.library.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 字符串操作工具包
 */
@SuppressLint("SimpleDateFormat")
public class StringUtils {

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * 获取打码后字符
     *
     * @param str
     * @return
     */
    public static String getMosaic(String str) {
        if (StringUtils.isEmptyOrNull(str) || str.length() <= 2) {
            return str;
        }
        return str.substring(0, 1) + "**" + str.substring(str.length() - 1);
    }

    /**
     * 判断是否包含Emoji表情
     *
     * @param str
     * @return
     */
    public static boolean containsEmoji(String str) {
        int len = str.length();
        for (int i = 0; i < len; i++) {
            if (isEmojiCharacter(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime() {
        return getDataTime("HH:mm");
    }

    /**
     * 毫秒值转换为mm:ss
     *
     * @param ms
     * @author kymjs
     */
    public static String timeFormat(int ms) {
        StringBuilder time = new StringBuilder();
        time.delete(0, time.length());
        ms /= 1000;
        int s = ms % 60;
        int min = ms / 60;
        if (min < 10) {
            time.append(0);
        }
        time.append(min).append(":");
        if (s < 10) {
            time.append(0);
        }
        time.append(s);
        return time.toString();
    }

    /**
     * 将字符串转位日期类型
     *
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     */
    public static boolean isEmpty(String input) {
        return input == null || "".equals(input);
    }

    /***
     * 判断字符串是否null，或""，或"null"
     *
     * @param source
     * @return
     */
    public static boolean isEmptyOrNull(String source) {
        return source == null || "".equals(source) || "null".equals(source);
    }

    public static String[] split(String source, String subStr) {
        return source.split(subStr);
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * String转long
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * String转double
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static double toDouble(String obj) {
        try {
            return Double.parseDouble(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0D;
    }

    /**
     * 字符串转布尔
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 判断一个字符串是不是数字
     */
    public static boolean isNumber(String str) {
        try {
            Integer.parseInt(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取AppKey
     */
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai =
                    context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    /**
     * KJ加密
     */
    public static String KJencrypt(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c + 5));
        }
        return hex.toString();
    }

    /**
     * KJ解密
     */
    public static String KJdecipher(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c - 5));
        }
        return hex.toString();
    }

    /**
     * 数组转String，用逗号分隔
     *
     * @param values
     * @return
     */
    public static String arrayToString(String[] values) {
        if (null == values) return "";

        StringBuffer buffer = new StringBuffer(values.length);
        for (int i = 0; i < values.length; i++) {
            buffer.append(values[i]).append(",");
        }
        if (buffer.length() > 0) {
            return buffer.toString().substring(0, buffer.length() - 1);
        }
        return "";
    }

    /**
     * 判断字符串数组是否含有某个字符串
     *
     * @param stringArray
     * @param source
     * @return
     */
    public static boolean contains(String[] stringArray, String source) {
        // 转换为list
        List<String> tempList = Arrays.asList(stringArray);

        // 利用list的包含方法,进行判断
        if (tempList.contains(source)) {
            return true;
        } else {
            return false;
        }
    }

    public static String map2JsonStr(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            sb.append("\"" + key + "\":\"" + map.get(key) + "\",");
        }
        String s = sb.toString();
        return "{" + s.substring(0, s.length() - 1) + "}";
    }

    //显示分数样式  1/2
    public static String showAofBth(Object a, Object b) {
        Object A = a.toString().trim();
        Object B = b.toString().trim();
        return A.toString() + "/" + B.toString();

/*        if (A instanceof Integer || A instanceof Long || A instanceof Float || A instanceof Double) {
            if (B instanceof Integer || B instanceof Long || B instanceof Float || B instanceof Double) {
                return A.toString() + "/" + B.toString();
            }
        }
        return "";*/
    }

    /**
     * 格式化银行卡
     *
     * @param num  银行卡号
     * @param step 间隔
     * @return 新生成的银行卡号
     */
    public static String addStrStepFromHead(String num, int step, String addStr) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(num)) {
            int length = num.length();
            int result = length % step;
            for (int i = 0; i < length / step; i++) {
                sb.append(num.substring(step * i, step * (i + 1))).append(addStr);
            }
            sb.append(num.substring(length - result, length));
        }
        return sb.toString();
    }

    /**
     * 格式化银行卡
     *
     * @param num  银行卡号
     * @param step 间隔
     * @return 新生成的银行卡号
     */
    public static String addStrStepFromEnd(String num, int step, String addStr) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(num)) {
            int length = num.length();
            int result = length % step;
            if (result > 0) {
                sb.append(num.substring(0, result));
                for (int i = 0; i < length / step; i++) {
                    sb.append(addStr).append(num.substring(result + i * step, result + (i + 1) * step));
                }
            } else {
                for (int i = 0; i < length / step; i++) {
                    sb.append(num.substring(i * step, (i + 1) * step));
                    if (i != length / step - 1) {
                        sb.append(addStr);
                    }
                }
            }

        }
        return sb.toString();
    }


    /**
     */
    public static String formatMoney(String money) {
        StringBuilder sb = new StringBuilder();
        String moneyStr = String.valueOf(money);
        if (moneyStr.contains("\\.")) {
            String[] split = moneyStr.split("\\.");
            String str1 = split[0];
            String str2 = split[1];
            String result = addStrStepFromEnd(str1, 3, ",");
            sb.append(result).append(".").append(str2);
        } else {
            String result = addStrStepFromEnd(moneyStr, 3, ",");
            sb.append(result);
        }
        return sb.toString();
    }



}